﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using QWeiBoN.Util;
using TencentWeiboSDK.Model;
using Microsoft.Phone.Tasks;
using Microsoft.Phone.Shell;
using QWeiBoN.ViewModule;
using System.Windows.Media.Imaging;

namespace QWeiBoN.UserControler
{
    public partial class AddStatus : PhoneApplicationPage
    {

        #region 私有属性

        /// <summary>
        /// 微博处理类
        /// </summary>
        private MainPostNewModel pModel = new MainPostNewModel();
        private RepostTextModel rtModel = new RepostTextModel();

        /// <summary>
        /// 是否显示选择表情或者话题或者提及
        /// </summary>
        private bool isShowPop { get; set; }

        /// <summary>
        /// 添加类型
        /// </summary>
        private AddStatusType addType { get; set; }

        /// <summary>
        /// 父微博对象
        /// </summary>
        private Status fatherStatus { get; set; }

        /// <summary>
        /// 发私信时使用，内容为收信人name
        /// </summary>
        private string metaData { get; set; }

        /// <summary>
        /// 微博内容草稿帮助类
        /// </summary>
        StatusContentHelper contentHelper = new StatusContentHelper();

        #endregion

        public AddStatus()
        {
            InitializeComponent();
            AddContent.Text = "";
            this.ApplicationBar.BackgroundColor = (Color)App.Current.Resources["ApplicationBarBackground"];
        }

        #region 导航服务处理

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);

            AddTextCount.Text = string.Format("({0})", AppSetting.MaxStatusContentCount);
            AddContent.Text = string.Empty;

            FaceSelect.Selected = FaceSelected;
            UserSelect.Selected = UserSelected;
            TopicsSelect.Selected = TopicsSelected;

            if (NavigationContext.QueryString.ContainsKey(AppSetting.AddStatusTypeKey))
            {
                var typeString = NavigationContext.QueryString[AppSetting.AddStatusTypeKey];
                if (!string.IsNullOrWhiteSpace(typeString))
                {
                    addType = (AddStatusType)int.Parse(typeString);
                    // 设置标题
                    if (addType != AddStatusType.Mention && addType != AddStatusType.PrivateMessage)
                    {
                        if (addType == AddStatusType.ReAdd)
                        {
                            AddTitle.Text = "转播微博";
                        }
                        else if (addType == AddStatusType.Reply)
                        {
                            AddTitle.Text = "回复微博";
                        }
                        else
                        {
                            AddTitle.Text = "对话";
                        }

                        //设置按钮
                        this.ApplicationBar.Buttons.RemoveAt(1); // 图片按钮不可用
                        this.ApplicationBar.MenuItems.RemoveAt(0); // 清除图片按钮不可用

                        Status tmpStatus = new Status();
                        if (IsoSetting.Get<Status>(IsoHelper.FatherStatusKey, out tmpStatus))
                        {
                            fatherStatus = tmpStatus;
                            if (null != fatherStatus)
                            {
                                // 是回复或者转播，在微博的内容上加入这条微博的内容
                                if (addType != AddStatusType.Comment && (fatherStatus.Type == (int)EStatusType.Forward || fatherStatus.Type == (int)EStatusType.Reply) && fatherStatus.Source != null)
                                {
                                    AddContent.Text = "||@" + fatherStatus.Name + "：" + fatherStatus.Origtext;
                                    fStatus.Text = string.Format("{0}：{1}", fatherStatus.Source.Nick, fatherStatus.Source.Origtext);
                                }
                                else
                                {
                                    fStatus.Text = string.Format("{0}：{1}", fatherStatus.Nick, fatherStatus.Origtext);
                                }
                            }
                        }
                    }
                    else if (addType != AddStatusType.PrivateMessage)
                    {
                        string name = NavigationContext.QueryString[AppSetting.AddStatusMetaParameterKey];
                        AddTitle.Text = "@" + name;
                        string tmpStr = "@" + name;
                        if (NavigationContext.QueryString.ContainsKey(AppSetting.AddStatusSubMetaParameterKey))
                        {
                            tmpStr += " " + HttpUtility.UrlDecode(NavigationContext.QueryString[AppSetting.AddStatusSubMetaParameterKey]);
                        }
                        AddContent.Text = tmpStr;
                        AddContent.SelectionStart = AddContent.Text.Length;
                        AddContent.Focus();
                    }
                    else
                    {
                        string name = NavigationContext.QueryString[AppSetting.AddStatusMetaParameterKey];
                        metaData = name;
                        AddTitle.Text = "私信：" + name;
                    }
                }
            }
            if (addType == AddStatusType.Add)
            {
                string draftStr = contentHelper.Get();
                if (!string.IsNullOrWhiteSpace(draftStr))
                {
                    AddContent.Text = draftStr;
                    AddContent.SelectionStart = AddContent.Text.Length;
                    AddContent.Focus();
                }
            }
        }

        protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedFrom(e);

            if (addType == AddStatusType.Add)
            {
                contentHelper.Save(AddContent.Text);
            }
        }

        #endregion


        #region 页面操作事件和方法
        /// <summary>
        /// 图片按钮的事件处理方法
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ImageBtn_Click(object sender, EventArgs e)
        {
            var imageTask = new PhotoChooserTask { ShowCamera = true };
            imageTask.Completed += imageTask_Completed;
            imageTask.Show();
        }

        /// <summary>
        /// PhotoChooserTask的事件处理方法
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void imageTask_Completed(object sender, PhotoResult e)
        {
            try
            {
                if (null != e.ChosenPhoto)
                {
                    // 显示清空图片menuitem
                    ((ApplicationBarMenuItem)this.ApplicationBar.MenuItems[0]).IsEnabled = true;
                    imgPhotoIcon.Visibility = Visibility.Visible;
                    if (string.IsNullOrWhiteSpace(AddContent.Text))
                    {
                        AddContent.Text = "#分享图片#";
                    }
                    // 这里设置需要上传的图片
                    BitmapImage imageSource = new BitmapImage();
                    imageSource.SetSource(e.ChosenPhoto);
                    pModel.ImageSource = imageSource;
                    imgPhotoIcon.Source = imageSource;
                    imgPhotoIcon.Visibility = Visibility.Visible;
                }
            }
            catch
            {
            }
        }

        /// <summary>
        /// 表情按钮的事件处理方法
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void FaceBtn_Click(object sender, EventArgs e)
        {
            if (isShowPop) { return; }
            isShowPop = true;
            CloseKeyboard();
            AddProgressBar.IsIndeterminate = true;
            FaceSelect.Show(() =>
            {
                AddProgressBar.IsIndeterminate = false;
            });
        }

        /// <summary>
        /// 隐藏输入法
        /// </summary>
        private void CloseKeyboard()
        {
            Dispatcher.BeginInvoke(() => CBtn.Focus());
        }

        /// <summary>
        /// 表情图片选中处理
        /// </summary>
        /// <param name="face"></param>
        private void FaceSelected(string face)
        {
            Dispatcher.BeginInvoke(() =>
            {
                isShowPop = false;
                InnerAddContent(face);
                FaceSelect.Hide();
                AddContent.Focus();
            });
        }

        /// <summary>
        /// 查找用户后的用户选中处理
        /// </summary>
        /// <param name="user"></param>
        private void UserSelected(User user)
        {
            Dispatcher.BeginInvoke(() =>
            {
                isShowPop = false;
                InnerAddContent("@" + user.Name);
                UserSelect.Hide();
                AddContent.Focus();
            });
        }

        /// <summary>
        /// 话题选择处理
        /// </summary>
        /// <param name="topicsStr"></param>
        private void TopicsSelected(string topicsStr)
        {
            Dispatcher.BeginInvoke(() =>
            {
                isShowPop = false;
                InnerAddContent(topicsStr);
                TopicsSelect.Hide();
                AddContent.Focus();
            });
        }

        /// <summary>
        /// 在内容框中插入文字
        /// </summary>
        /// <param name="content"></param>
        public void InnerAddContent(string content)
        {
            Dispatcher.BeginInvoke(() =>
            {
                if (AddContent.SelectedText.Length < 0)
                {
                    AddContent.Select(AddContent.SelectionStart, AddContent.Text.Length - AddContent.SelectionStart);
                    AddContent.SelectedText = content + AddContent.SelectedText;
                    AddContent.SelectionStart += content.Length;
                }
                else
                {
                    AddContent.SelectedText = content;
                }
                AddContent.Focus();
            });
        }

        /// <summary>
        /// 窗体返回按钮的事件处理方法
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void PhoneApplicationPage_BackKeyPress(object sender, System.ComponentModel.CancelEventArgs e)
        {
            if (isShowPop)
            {
                isShowPop = false;
                FaceSelect.Hide();
                UserSelect.Hide();
                TopicsSelect.Hide();
                e.Cancel = true;
            }
            else
            {
                if (NavigationContext.QueryString.ContainsKey(AppSetting.IsQuickAddStatusParameterKey))
                {
                    App.Quit();
                }
            }
        }

        /// <summary>
        /// 清除图片按钮的事件处理方法
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ClearImage_Click(object sender, EventArgs e)
        {
            imgPhotoIcon.Visibility = Visibility.Collapsed;
            imgPhotoIcon.Source = null;
            // 下面清除存放图片的对象
            pModel.ImageSource = null;
        }

        /// <summary>
        /// 清除文字按钮的事件处理放啊
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ClearContent_Click(object sender, EventArgs e)
        {
            AddContent.Text = string.Empty;
        }

        /// <summary>
        /// 微博内容输入框的内容改变事件处理方法
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void AddContent_TextChanged(object sender, TextChangedEventArgs e)
        {
            AddTextCount.Text = string.Format("({0})", AppSetting.MaxStatusContentCount - AddContent.Text.Length);
        }

        /// <summary>
        /// 微博内容输入框获得焦点事件处理方法
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void AddContent_GotFocus(object sender, RoutedEventArgs e)
        {
            AddContent.BorderThickness = new Thickness(1);
            AddContent.BorderBrush = new SolidColorBrush(Color.FromArgb(255, 189, 190, 189));
        }

        /// <summary>
        /// 微博内容输入框失去焦点事件处理方法
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void AddContent_LostFocus(object sender, RoutedEventArgs e)
        {
            AddContent.BorderThickness = new Thickness(1);
            AddContent.BorderBrush = new SolidColorBrush(Color.FromArgb(255, 189, 190, 189));
        }

        /// <summary>
        /// 发送itembutton的事件处理方法
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SendBtn_Click(object sender, EventArgs e)
        {
            CloseKeyboard();
            AddProgressBar.IsIndeterminate = true;

            if (addType == AddStatusType.ReAdd) // 转播
            {
                // 判断二次转播
                if ((fatherStatus.Type == (int)EStatusType.Forward || fatherStatus.Type == (int)EStatusType.Reply) && null != fatherStatus.Source)
                {
                    ReAddStatusMethod(fatherStatus.Source.Id, AddContent.Text);
                }
                else
                {
                    ReAddStatusMethod(fatherStatus.Id, AddContent.Text);
                }
            }
            else if(addType == AddStatusType.Add)
            {

                // 以下是处理点击发送新微博的按钮的方法
                pModel.Text = this.AddContent.Text;
                //发送微博，在这里可以提示用户正在发送，或者切换回上一个页面
                pModel.Post(() =>
                {
                    // 回调回来后可以通知用户已经发送成功或失败
                    // 同时加载最新的微博数据
                    //Refresh();
                    Dispatcher.BeginInvoke(() =>
                    {
                        AddContent.Text = string.Empty;
                        //NavigationService.Navigate(new Uri(string.Format("/MainPage.xaml"), UriKind.Relative));
                        NavigationService.GoBack();
                    });
                });
            }
        }

        /// <summary>
        /// 窗体载入完成事件处理
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
        {
            //AddContent.Text = string.Empty;
        }

        /// <summary>
        /// 提及按钮的事件处理
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MentionedBtn_Click(object sender, EventArgs e)
        {
            if (isShowPop)
            {
                return;
            }
            isShowPop = true;
            CloseKeyboard();
            UserSelect.Show();
        }

        /// <summary>
        /// 插入话题按钮的事件处理
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void AddTopic_Click(object sender, EventArgs e)
        {
            if (isShowPop)
            {
                return;
            }
            isShowPop = true;
            CloseKeyboard();
            TopicsSelect.Show();
        }

        /// <summary>
        /// 返回前一页的事件处理
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BackBtn_Click(object sender, EventArgs e)
        {
            NavigationService.GoBack();
        }

        /// <summary>
        /// 返回主页的事件处理
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void HomeBtn_Click(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative));
        }

        #endregion

        #region 网络操作

        /// <summary>
        /// 用于进行微博的转发
        /// </summary>
        private void ReAddStatusMethod(string weiboId, string text)
        {
            rtModel.repostUserText(weiboId, text, null, (callback) =>
            {
                AddContent.Text = string.Empty;
                IsoSetting.Remove(IsoHelper.FatherStatusKey);
                NavigationService.Navigate(new Uri(string.Format("/MainPage.xaml"), UriKind.Relative));
            });
        }

        #endregion

    }
}